package io.summer.demo.examples;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkProxy {
  interface IHello {
    void sayHello();
    void bye();
  }

  static class Hello implements IHello {
    public void sayHello() {
      System.out.println("hello world");
    }

    @Override
    public void bye() {
      System.out.println("bye!");
    }
  }

  static class HelloProxyTest implements InvocationHandler {
    Object originalObj;
    Object bind(Object originalObj) {
      this.originalObj = originalObj;
      return Proxy.newProxyInstance(originalObj.getClass().getClassLoader(),
        originalObj.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      System.out.println("InvocationHandler invoked: " + method.getName());
      return method.invoke(originalObj, args);
    }
  }

  public static void main(String[] args) {
    //设置这个值，在程序运行完成后，可以生成代理类
//    System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
    IHello hello = (IHello) new HelloProxyTest().bind(new Hello());
    hello.sayHello();
    hello.bye();
  }
}
